// xc_lshop/recharge/index/infor.js
// var actbill = require('../../../xc/model/huka')
// var order_bill = require('../../../xc/model/order_bill.js')
var actbill = require('../../model/huka')
const app = getApp()

Page({
  mixins: [require('../../../../xc/mixins/basicMixin')],
  
  /**
   * 页面的初始数据
   */
  data: {
    basicurl: -1,
    specid: "",
    number: "",
    tipshow: true,
    brand: [{
        name: "星巴克",
        imgurl: "https://app.xdjxm.com/tem/a.png"
      },
      {
        name: "必胜客",
        imgurl: "https://app.xdjxm.com/tem/b.png"
      },
      {
        name: "肯德基",
        imgurl: "https://app.xdjxm.com/tem/c.png"
      },
      {
        name: "COCO",
        imgurl: "https://app.xdjxm.com/tem/d.png"
      },
      {
        name: "百果园",
        imgurl: "https://app.xdjxm.com/tem/e.png"
      },
      {
        name: "美团",
        imgurl: "https://app.xdjxm.com/tem/ca.png"
      },
      {
        name: "饿了么",
        imgurl: "https://app.xdjxm.com/tem/cb.png"
      },
      {
        name: "肯德基",
        imgurl: "https://app.xdjxm.com/tem/cc.png"
      },
      {
        name: "电影",
        imgurl: "https://app.xdjxm.com/tem/cd.png"
      },
      {
        name: "寄售",
        imgurl: "https://app.xdjxm.com/tem/ce.png"
      },
    ],
    payprice:-1

  },
  xcloaddata: function (options, config) {
    // console.log("config")
    // var num=0.105
    // console.log(Number.EPSILON)
    // console.log(config)
    // console.log(config.hukaapi)

    if(config && config.hukaapi){
      this.setData({
        hukaapiconfig: config.hukaapi
      })
      if(config.hukaapi.status==-1){
        this.pageback()
      }
    }else{
      this.error("该功能尚未配置", true);
    }
    this.setData({
      strtype:options.strtype
    })
    this.getmodel(options)
    // this.orderquery(80)
    
  },
  showtip() {
    this.setData({
      tipshow: !this.data.tipshow
    })
  },
  getmodel(options) {
    var that = this;

    actbill.getmodel(options.gid, options.strtype).then(function (res) {

      console.log("getmodel");
      console.log(res['pro']);
      console.log(res['config']);
      console.log(res['data']);

      if (res['status'] == 1) {
        var update={};
        if(res['data']){
          update['xcmodel']=res['data'];
        }
        if(res['pro']){
          update['proconfig']=res['pro'];
        }
        if(res['config']){
          update['priceconfig']=res['config'];
        }

        that.setData(update)
      }

    })
  },
  choosespec(e) {
    var id = e.currentTarget.dataset.id;
    var sellprice = e.currentTarget.dataset.sellprice;

    this.setData({
      specid: id,
      payprice:sellprice
    })
  },
  //创建订单
  createorder(){
    var that = this;
    app.xc_sys_config.authop.oppower("login").then(function (res) {
      that._createorder()
    })
  },
  _createorder() {
    var that = this;
    if(!this.data.member.member_id){
      this.login();
      return;
    }
    var ordermodel = {};
    var error = "";
    if(this.data.strtype=='recharge'){
      if (this.data.number) {
        ordermodel['number'] = this.data.number;
      } else {
        error += "[" + this.data.xcmodel.account_type + "]"
      }  
    }
 
    if (this.data.specid) {
      ordermodel['specid'] = this.data.specid;
    } else {
      error += "[规格]";
    }

    if (error) {
      wx.showModal({
        title: '提示',
        content: '请输入' + error,
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      var obj = that.data.xcmodel.spec.find(function (item) {
        return item.spec_id == that.data.specid
      })
      console.log(obj)
      ordermodel['gid']=this.data.xcmodel.g_id;
      ordermodel['strtype']=this.data.strtype;
      ordermodel['paytype']=1;
      ordermodel['totalprice']=this.data.payprice;

      // this.postorder(ordermodel)
      // return;
      // var message=
      var time="";
      if(obj.times){
        time=obj.times
      }

      var text="";
      if(this.data.number){
        text +='账户：' + this.data.number+'\r\n'
      }
      text +='规格：' + obj.title + time + '\r\n'
      text +='价格：' + this.data.payprice
      
      wx.showModal({
        title: '确认订单',
        content: text,
        success(res) {
          if (res.confirm) {
            that.postorder(ordermodel)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })

    }


  },
  //已登入传参数
  afterlogin: function (options, config, userinfo) {
    var that = this;
    that.setData({
      "member": userinfo
    })
  },
  // 登录注册
  login(e) {
    var that = this;
    var app=getApp();
    app.xc_sys_config.authop.oppower("login").then(function (res) {
      that.setData({
        "member": app.globalData.member
      })
    })
  },
  //提交订单
  postorder(ordermodel) {
    var that = this;
    actbill.createorder(ordermodel).then(function (restmodel) {
      if (restmodel["status"] == 1) {
      
        // var template_ids = restmodel["template_ids"]
        //  template_ids=["SumpUZ0J0kB_jQ3uFhgfxcYjCngZPP45yHPpnFxcKWs","1uZEExJ1levUgB2hFlGFox6mWdxkIFAil8fSQkUxLY8","EYmkv8o3hh9Mugu4YNhDP2zbnpdYpawWghaaOSPlOyI"]

        // console.log(template_ids)
        // if (restmodel["paytype"] == 1 || restmodel["paytype"] == 3) {
          var pay_params = restmodel["pay_params"];
          var template_ids = restmodel["template_ids"];

          wx.requestPayment({
            timeStamp: pay_params["timeStamp"],
            nonceStr: pay_params["nonceStr"],
            package: pay_params["package"],
            signType: pay_params['signType'],
            paySign: pay_params["paySign"],
            success(res) {
              that.orderquery(restmodel["id"],template_ids,restmodel["ordernum"])
              
            },
            fail(res) {
              if (res["errMsg"] == "requestPayment:fail cancel") {
                wx.showModal({
                  title: '订单未支付',
                  content: '订单未支付',
                  showCancel: false,
                  success(res) {
                    console.log("wx.redirectTo959595959")

                    // wx.redirectTo({
                    //   url: "/xc_lshop/shop/order/index?opstatus=-1",
                    // })
                  }
                })
              }

            }
          })
        // } else if (restmodel["paytype"] == 2) {
        //   //余额支付
        //   console.log("余额支付")
        //   console.log("wx.redirectTo44851125456")


        //   that.showtemplate(template_ids, restmodel['ordernum'], restmodel["id"])


        // }
      } else {
        wx.showModal({
          title: '错误',
          content: restmodel["message"],
        })
      }
    })
  },

 
  //订单查询
  orderquery(id,template_ids,ordernum){
    var that=this;
    actbill.queryorder(id).then(function (queryreslut) {
      if (queryreslut["status"] == 1) {
        console.log("wx.redirectTo44848484844")
        that.showtemplate(template_ids, id,ordernum)
        // wx.redirectTo({
        //   url: "/xc_lshop/shop/order/info?id="+id,
        // })

        
        
      }
    })
  },
  showtemplate(template_ids,id,ordernum){
    var that=this;
    if (template_ids && template_ids.length > 0) {
      if(template_ids.length > 3){
        template_ids=template_ids.slice(0,3)
      }
      console.log("template_ids88888888888888888")
      console.log(template_ids)
      wx.requestSubscribeMessage({
        tmplIds: template_ids,
        success(res) {
     
          that.sendnotice(ordernum)
        },fail(res){
       
      
         },
         complete(res){
       
          wx.redirectTo({
            url: "/xc_lshop/shop/order/info?id="+id,
          })
          // wx.redirectTo({
          //   url: "/xc_lshop/shop/order/index?opstatus=-1",
          // })
          // wx.redirectTo({
          //   url: '/xc_lshop/shop/paycore/paysuccess?id=' +id,
          // })
         }
      })
    }else{
      wx.redirectTo({
        url: "/xc_lshop/shop/order/info?id="+id,
      })
    }
  },
  sendnotice(ordernum){
    actbill.sendnotice(ordernum).then(function (restmodel) {
      console.log(restmodel)
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  
})